package org.niugang.aop;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.niugang.annotation.LogApi;
import org.niugang.utils.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
/**
 * 记录日志的aop
 * Copyright: Copyright (c) 2018 863263957@qq.com
 * 
 * @ClassName: LogAscept.java
 * @version: v1.0.0
 * @author: niugang
 * @date: 2018年9月18日 下午5:38:23
 */
@Aspect
@Component
public class LogAscept {
    

	@Autowired
	private RabbitTemplate rabbitTemplate;

    /**
      * 开始时间
     */
	private long start;
	/**
	 * 结束时间
	 */
	private long end;

	/**
	 * ip
	 */
	private String ip;

	/**
	 * 端口
	 */
	private int port;
  
	@Value("${log.exchange.name}")
	private String exchange;
	
	@Value("${log.route.key.name}")
	private String routeKey;
	
	@Around("@annotation(org.niugang.annotation.LogApi)")
	public Object aroundAdvice(ProceedingJoinPoint pjd) throws Throwable {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes r = (ServletRequestAttributes) requestAttributes;
		HttpServletRequest request = r.getRequest();
		start = System.currentTimeMillis();
		Object proceed = pjd.proceed();
		end = System.currentTimeMillis();
		ip = getIpAddr(request);
		port = request.getRemotePort();
		MethodSignature signature = (MethodSignature) pjd.getSignature();
		Method method = signature.getMethod();
		LogApi logApi = method.getAnnotation(LogApi.class);
		// 调用redis发布消息
		messageQueue(logApi);
		return proceed; // 必须得有返回值，否则不能往下执行
	}
   /**
    * 
    * @Title: messageQueue
    * @Description: 发布消息
    * @param logApi    
    * @return void    
    * @throws
    */
	private void messageQueue(LogApi logApi) {
		String value = logApi.value();
		String type = logApi.type();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("value", value);
		jsonObject.put("type", type);
		jsonObject.put("ip", ip);
		jsonObject.put("port", port);
		jsonObject.put("useTime", (end-start));
		jsonObject.put("time",DateUtils.format(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		
		//执行保存
		String uuid = UUID.randomUUID().toString();
		CorrelationData correlationId = new CorrelationData(uuid);

		Message message = MessageBuilder.withBody(jsonObject.toString().getBytes()).build();
		// 发送消息
		rabbitTemplate.send(exchange, routeKey, message, correlationId);


	}
    /**
     * 
     * @Title: getIpAddr
     * @Description: 处理ip
     * @param request
     * @return    
     * @return String    
     * @throws
     */
	public static String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}


}